# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date:
# @Last Modified by: CPS
# @Last Modified time: 2021-04-12 03:42:45.822704
# @file_path "D:\CPS\IDE\JS_SublmieText\Data\Packages\CPS\core"
# @Filename "file_header.py"
# @Description: 功能描述
#

if ( __name__ == "__main__"):
    pass


import sublime
import sublime_plugin
import datetime
import os

from .core import settings
from .core.utils import env

TMPL_PATH = ""


def get_user_select_syntax(index):
    if index != -1:
        sublime.active_window().run_command("testt_add_file_header", {"syntaxIndex": index})


class TesttAddFileHeaderCommand(sublime_plugin.TextCommand):
    def run(self, edit, syntaxIndex=-1):
        if not TMPL_PATH:
            self.set_tmpl_path(env.get_plugin_name())

        try:
            size = self.view.sel()[0].end()
            file_name = self.view.file_name()
            tmp_file = self.get_tmpl_file(file_name)

            if isinstance(tmp_file, dict):
                if syntaxIndex > -1:
                    tmp_file = tmp_file[list(tmp_file.keys())[int(syntaxIndex)]]
                    print('当前tmp_file: ', tmp_file)
                else:
                    sublime.active_window().show_quick_panel(tmp_file.keys(), get_user_select_syntax)
                    return

            info = self.get_header_info(file_name,size)
            header_info = self.replace_tmpl_info(tmp_file,info)

            if header_info:
                self.insert_file_header(edit, header_info)

        except Exception as e:
            print('TesttAddFileHeaderCommand，发生错误: ' + e)


    def insert_file_header(self, edit, header_info):
        cursor_offset = self.view.sel()[0].end()
        self.view.insert(edit,0,header_info) and self.view.show_at_center(cursor_offset)


    def set_tmpl_path(self, plugin_name):
        global TMPL_PATH
        TMPL_PATH = os.path.join(sublime.packages_path(),plugin_name,"headerTmpl")

    def get_tmpl_path():
        return TMPL_PATH

    def insertFileHeader(self,filename, size=0):
        _settings = settings.get_settings()
        _options = settings.get_options('file_header')

        info = _options['headerInfo']

        # 文件字符串少于2的话,当作是一个新文件,添加创建时间
        if size <= 1:
            info = on_add_file(filename, info)
        info = on_modi_file(filename, info)

    def get_header_info(self,filename, size=0):
        _settings = settings.get_settings()
        _options = settings.get_options('file_header')
        info = _options['headerInfo']

        # 文件字符串少于2的话,当作是一个新文件,添加创建时间
        if size <= 1:
            info = self.on_add_file(filename, info)
        info = self.on_modi_file(filename, info)
        return info

    def get_header_settings(self):
        return settings.get_settings().get_options('file_header')

    def get_tmpl_file(self, filename):
        _settings = settings.get_options('file_header')
        _template = _settings['template']
        ext = os.path.splitext(filename)[1].replace('.','').lower()
        if ext in _template.keys():
            if isinstance(_template[ext],list):
                # 弹出选项
                print('当前是列表中： ',_template[ext])
                # res = sublime.active_window().showSelectPanel(_template[ext])
                res={}
                for each in _template[ext]:
                    res[each] = os.path.join(TMPL_PATH,each)+'.tmpl'
                return  res

            else:
                res = os.path.join(TMPL_PATH,_template[ext])+'.tmpl'
                return res

        return False

    def replace_tmpl_info(self,tmpl_file, info):
        if os.path.exists(tmpl_file):
            # 读取tmpl文件
            res = ''
            with open(tmpl_file,'r',encoding='utf8') as tmpl:
                for each in tmpl.readlines():
                    for key,val in info.items():
                        each = each.replace('{{'+key+'}}',val)
                    res+=each
            return res


    def on_add_file(self,filename,info):
        info['create_time'] = self.get_now(info['create_time'])
        return info

    def on_modi_file(self,filename, info):
        info['last_modified_time'] = self.get_now(info['last_modified_time'])
        info['file_path'] = os.path.dirname(filename)
        fn = os.path.basename(filename)

        if fn.startswith('index'):
          # 如果文件是 index.xxxx, 就把文件夹名作为文件名
          info['file_name'] = os.path.basename(info['file_path'])
        else:
          info['file_name'] = fn

        return info

    def get_now(self,fmat = r'%Y-%m-%d %H:%M:%S'):
        return datetime.datetime.now().__format__(fmat)

